home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / email / Message.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2005-10-18  |  28.1 KB  |  849 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Basic message object for the email package object model.'''
  5. import re
  6. import uu
  7. import binascii
  8. import warnings
  9. from cStringIO import StringIO
  10. from email import Utils
  11. from email import Errors
  12. from email import Charset
  13. SEMISPACE = '; '
  14. paramre = re.compile('\\s*;\\s*')
  15. tspecials = re.compile('[ \\(\\)<>@,;:\\\\"/\\[\\]\\?=]')
  16.  
  17. def _formatparam(param, value = None, quote = True):
  18.     '''Convenience function to format and return a key=value pair.
  19.  
  20.     This will quote the value if needed or if quote is true.
  21.     '''
  22.     if value is not None and len(value) > 0:
  23.         if isinstance(value, tuple):
  24.             param += '*'
  25.             value = Utils.encode_rfc2231(value[2], value[0], value[1])
  26.         
  27.         if quote or tspecials.search(value):
  28.             return '%s="%s"' % (param, Utils.quote(value))
  29.         else:
  30.             return '%s=%s' % (param, value)
  31.     else:
  32.         return param
  33.  
  34.  
  35. def _parseparam(s):
  36.     plist = []
  37.     while s[:1] == ';':
  38.         s = s[1:]
  39.         end = s.find(';')
  40.         while end > 0 and s.count('"', 0, end) % 2:
  41.             end = s.find(';', end + 1)
  42.         if end < 0:
  43.             end = len(s)
  44.         
  45.         f = s[:end]
  46.         if '=' in f:
  47.             i = f.index('=')
  48.             f = f[:i].strip().lower() + '=' + f[i + 1:].strip()
  49.         
  50.         plist.append(f.strip())
  51.         s = s[end:]
  52.     return plist
  53.  
  54.  
  55. def _unquotevalue(value):
  56.     if isinstance(value, tuple):
  57.         return (value[0], value[1], Utils.unquote(value[2]))
  58.     else:
  59.         return Utils.unquote(value)
  60.  
  61.  
  62. class Message:
  63.     """Basic message object.
  64.  
  65.     A message object is defined as something that has a bunch of RFC 2822
  66.     headers and a payload.  It may optionally have an envelope header
  67.     (a.k.a. Unix-From or From_ header).  If the message is a container (i.e. a
  68.     multipart or a message/rfc822), then the payload is a list of Message
  69.     objects, otherwise it is a string.
  70.  
  71.     Message objects implement part of the `mapping' interface, which assumes
  72.     there is exactly one occurrance of the header per message.  Some headers
  73.     do in fact appear multiple times (e.g. Received) and for those headers,
  74.     you must use the explicit API to set or get all the headers.  Not all of
  75.     the mapping methods are implemented.
  76.     """
  77.     
  78.     def __init__(self):
  79.         self._headers = []
  80.         self._unixfrom = None
  81.         self._payload = None
  82.         self._charset = None
  83.         self.preamble = None
  84.         self.epilogue = None
  85.         self.defects = []
  86.         self._default_type = 'text/plain'
  87.  
  88.     
  89.     def __str__(self):
  90.         '''Return the entire formatted message as a string.
  91.         This includes the headers, body, and envelope header.
  92.         '''
  93.         return self.as_string(unixfrom = True)
  94.  
  95.     
  96.     def as_string(self, unixfrom = False):
  97.         '''Return the entire formatted message as a string.
  98.         Optional `unixfrom\' when True, means include the Unix From_ envelope
  99.         header.
  100.  
  101.         This is a convenience method and may not generate the message exactly
  102.         as you intend because by default it mangles lines that begin with
  103.         "From ".  For more flexibility, use the flatten() method of a
  104.         Generator instance.
  105.         '''
  106.         Generator = Generator
  107.         import email.Generator
  108.         fp = StringIO()
  109.         g = Generator(fp)
  110.         g.flatten(self, unixfrom = unixfrom)
  111.         return fp.getvalue()
  112.  
  113.     
  114.     def is_multipart(self):
  115.         '''Return True if the message consists of multiple parts.'''
  116.         return isinstance(self._payload, list)
  117.  
  118.     
  119.     def set_unixfrom(self, unixfrom):
  120.         self._unixfrom = unixfrom
  121.  
  122.     
  123.     def get_unixfrom(self):
  124.         return self._unixfrom
  125.  
  126.     
  127.     def attach(self, payload):
  128.         '''Add the given payload to the current payload.
  129.  
  130.         The current payload will always be a list of objects after this method
  131.         is called.  If you want to set the payload to a scalar object, use
  132.         set_payload() instead.
  133.         '''
  134.         if self._payload is None:
  135.             self._payload = [
  136.                 payload]
  137.         else:
  138.             self._payload.append(payload)
  139.  
  140.     
  141.     def get_payload(self, i = None, decode = False):
  142.         """Return a reference to the payload.
  143.  
  144.         The payload will either be a list object or a string.  If you mutate
  145.         the list object, you modify the message's payload in place.  Optional
  146.         i returns that index into the payload.
  147.  
  148.         Optional decode is a flag indicating whether the payload should be
  149.         decoded or not, according to the Content-Transfer-Encoding header
  150.         (default is False).
  151.  
  152.         When True and the message is not a multipart, the payload will be
  153.         decoded if this header's value is `quoted-printable' or `base64'.  If
  154.         some other encoding is used, or the header is missing, or if the
  155.         payload has bogus data (i.e. bogus base64 or uuencoded data), the
  156.         payload is returned as-is.
  157.  
  158.         If the message is a multipart and the decode flag is True, then None
  159.         is returned.
  160.         """
  161.         if i is None:
  162.             payload = self._payload
  163.         elif not isinstance(self._payload, list):
  164.             raise TypeError('Expected list, got %s' % type(self._payload))
  165.         else:
  166.             payload = self._payload[i]
  167.         if decode:
  168.             if self.is_multipart():
  169.                 return None
  170.             
  171.             cte = self.get('content-transfer-encoding', '').lower()
  172.             if cte == 'quoted-printable':
  173.                 return Utils._qdecode(payload)
  174.             elif cte == 'base64':
  175.                 
  176.                 try:
  177.                     return Utils._bdecode(payload)
  178.                 except binascii.Error:
  179.                     return payload
  180.                 except:
  181.                     None<EXCEPTION MATCH>binascii.Error
  182.                 
  183.  
  184.             None<EXCEPTION MATCH>binascii.Error
  185.             if cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
  186.                 sfp = StringIO()
  187.                 
  188.                 try:
  189.                     uu.decode(StringIO(payload + '\n'), sfp)
  190.                     payload = sfp.getvalue()
  191.                 except uu.Error:
  192.                     return payload
  193.                 except:
  194.                     None<EXCEPTION MATCH>uu.Error
  195.                 
  196.  
  197.             None<EXCEPTION MATCH>uu.Error
  198.         
  199.         return payload
  200.  
  201.     
  202.     def set_payload(self, payload, charset = None):
  203.         """Set the payload to the given value.
  204.  
  205.         Optional charset sets the message's default character set.  See
  206.         set_charset() for details.
  207.         """
  208.         self._payload = payload
  209.         if charset is not None:
  210.             self.set_charset(charset)
  211.         
  212.  
  213.     
  214.     def set_charset(self, charset):
  215.         '''Set the charset of the payload to a given character set.
  216.  
  217.         charset can be a Charset instance, a string naming a character set, or
  218.         None.  If it is a string it will be converted to a Charset instance.
  219.         If charset is None, the charset parameter will be removed from the
  220.         Content-Type field.  Anything else will generate a TypeError.
  221.  
  222.         The message will be assumed to be of type text/* encoded with
  223.         charset.input_charset.  It will be converted to charset.output_charset
  224.         and encoded properly, if needed, when generating the plain text
  225.         representation of the message.  MIME headers (MIME-Version,
  226.         Content-Type, Content-Transfer-Encoding) will be added as needed.
  227.  
  228.         '''
  229.         if charset is None:
  230.             self.del_param('charset')
  231.             self._charset = None
  232.             return None
  233.         
  234.         if isinstance(charset, str):
  235.             charset = Charset.Charset(charset)
  236.         
  237.         if not isinstance(charset, Charset.Charset):
  238.             raise TypeError(charset)
  239.         
  240.         self._charset = charset
  241.         if not self.has_key('MIME-Version'):
  242.             self.add_header('MIME-Version', '1.0')
  243.         
  244.         if not self.has_key('Content-Type'):
  245.             self.add_header('Content-Type', 'text/plain', charset = charset.get_output_charset())
  246.         else:
  247.             self.set_param('charset', charset.get_output_charset())
  248.         if not self.has_key('Content-Transfer-Encoding'):
  249.             cte = charset.get_body_encoding()
  250.             
  251.             try:
  252.                 cte(self)
  253.             except TypeError:
  254.                 self.add_header('Content-Transfer-Encoding', cte)
  255.             except:
  256.                 None<EXCEPTION MATCH>TypeError
  257.             
  258.  
  259.         None<EXCEPTION MATCH>TypeError
  260.  
  261.     
  262.     def get_charset(self):
  263.         """Return the Charset instance associated with the message's payload.
  264.         """
  265.         return self._charset
  266.  
  267.     
  268.     def __len__(self):
  269.         '''Return the total number of headers, including duplicates.'''
  270.         return len(self._headers)
  271.  
  272.     
  273.     def __getitem__(self, name):
  274.         '''Get a header value.
  275.  
  276.         Return None if the header is missing instead of raising an exception.
  277.  
  278.         Note that if the header appeared multiple times, exactly which
  279.         occurrance gets returned is undefined.  Use get_all() to get all
  280.         the values matching a header field name.
  281.         '''
  282.         return self.get(name)
  283.  
  284.     
  285.     def __setitem__(self, name, val):
  286.         '''Set the value of a header.
  287.  
  288.         Note: this does not overwrite an existing header with the same field
  289.         name.  Use __delitem__() first to delete any existing headers.
  290.         '''
  291.         self._headers.append((name, val))
  292.  
  293.     
  294.     def __delitem__(self, name):
  295.         '''Delete all occurrences of a header, if present.
  296.  
  297.         Does not raise an exception if the header is missing.
  298.         '''
  299.         name = name.lower()
  300.         newheaders = []
  301.         for k, v in self._headers:
  302.             if k.lower() != name:
  303.                 newheaders.append((k, v))
  304.                 continue
  305.         
  306.         self._headers = newheaders
  307.  
  308.     
  309.     def __contains__(self, name):
  310.         return [] in [ k.lower() for k, v in self._headers ]
  311.  
  312.     
  313.     def has_key(self, name):
  314.         '''Return true if the message contains the header.'''
  315.         missing = object()
  316.         return self.get(name, missing) is not missing
  317.  
  318.     
  319.     def keys(self):
  320.         """Return a list of all the message's header field names.
  321.  
  322.         These will be sorted in the order they appeared in the original
  323.         message, or were added to the message, and may contain duplicates.
  324.         Any fields deleted and re-inserted are always appended to the header
  325.         list.
  326.         """
  327.         return [ k for k, v in self._headers ]
  328.  
  329.     
  330.     def values(self):
  331.         """Return a list of all the message's header values.
  332.  
  333.         These will be sorted in the order they appeared in the original
  334.         message, or were added to the message, and may contain duplicates.
  335.         Any fields deleted and re-inserted are always appended to the header
  336.         list.
  337.         """
  338.         return [ v for k, v in self._headers ]
  339.  
  340.     
  341.     def items(self):
  342.         """Get all the message's header fields and values.
  343.  
  344.         These will be sorted in the order they appeared in the original
  345.         message, or were added to the message, and may contain duplicates.
  346.         Any fields deleted and re-inserted are always appended to the header
  347.         list.
  348.         """
  349.         return self._headers[:]
  350.  
  351.     
  352.     def get(self, name, failobj = None):
  353.         '''Get a header value.
  354.  
  355.         Like __getitem__() but return failobj instead of None when the field
  356.         is missing.
  357.         '''
  358.         name = name.lower()
  359.         for k, v in self._headers:
  360.             if k.lower() == name:
  361.                 return v
  362.                 continue
  363.         
  364.         return failobj
  365.  
  366.     
  367.     def get_all(self, name, failobj = None):
  368.         '''Return a list of all the values for the named field.
  369.  
  370.         These will be sorted in the order they appeared in the original
  371.         message, and may contain duplicates.  Any fields deleted and
  372.         re-inserted are always appended to the header list.
  373.  
  374.         If no such fields exist, failobj is returned (defaults to None).
  375.         '''
  376.         values = []
  377.         name = name.lower()
  378.         for k, v in self._headers:
  379.             if k.lower() == name:
  380.                 values.append(v)
  381.                 continue
  382.         
  383.         if not values:
  384.             return failobj
  385.         
  386.         return values
  387.  
  388.     
  389.     def add_header(self, _name, _value, **_params):
  390.         '''Extended header setting.
  391.  
  392.         name is the header field to add.  keyword arguments can be used to set
  393.         additional parameters for the header field, with underscores converted
  394.         to dashes.  Normally the parameter will be added as key="value" unless
  395.         value is None, in which case only the key will be added.
  396.  
  397.         Example:
  398.  
  399.         msg.add_header(\'content-disposition\', \'attachment\', filename=\'bud.gif\')
  400.         '''
  401.         parts = []
  402.         for k, v in _params.items():
  403.             if v is None:
  404.                 parts.append(k.replace('_', '-'))
  405.                 continue
  406.             parts.append(_formatparam(k.replace('_', '-'), v))
  407.         
  408.         if _value is not None:
  409.             parts.insert(0, _value)
  410.         
  411.         self._headers.append((_name, SEMISPACE.join(parts)))
  412.  
  413.     
  414.     def replace_header(self, _name, _value):
  415.         '''Replace a header.
  416.  
  417.         Replace the first matching header found in the message, retaining
  418.         header order and case.  If no matching header was found, a KeyError is
  419.         raised.
  420.         '''
  421.         _name = _name.lower()
  422.         for k, v in zip(range(len(self._headers)), self._headers):
  423.             if k.lower() == _name:
  424.                 self._headers[i] = (k, _value)
  425.                 break
  426.                 continue
  427.         else:
  428.             raise KeyError(_name)
  429.  
  430.     
  431.     def get_type(self, failobj = None):
  432.         """Returns the message's content type.
  433.  
  434.         The returned string is coerced to lowercase and returned as a single
  435.         string of the form `maintype/subtype'.  If there was no Content-Type
  436.         header in the message, failobj is returned (defaults to None).
  437.         """
  438.         warnings.warn('get_type() deprecated; use get_content_type()', DeprecationWarning, 2)
  439.         missing = object()
  440.         value = self.get('content-type', missing)
  441.         if value is missing:
  442.             return failobj
  443.         
  444.         return paramre.split(value)[0].lower().strip()
  445.  
  446.     
  447.     def get_main_type(self, failobj = None):
  448.         """Return the message's main content type if present."""
  449.         warnings.warn('get_main_type() deprecated; use get_content_maintype()', DeprecationWarning, 2)
  450.         missing = object()
  451.         ctype = self.get_type(missing)
  452.         if ctype is missing:
  453.             return failobj
  454.         
  455.         if ctype.count('/') != 1:
  456.             return failobj
  457.         
  458.         return ctype.split('/')[0]
  459.  
  460.     
  461.     def get_subtype(self, failobj = None):
  462.         """Return the message's content subtype if present."""
  463.         warnings.warn('get_subtype() deprecated; use get_content_subtype()', DeprecationWarning, 2)
  464.         missing = object()
  465.         ctype = self.get_type(missing)
  466.         if ctype is missing:
  467.             return failobj
  468.         
  469.         if ctype.count('/') != 1:
  470.             return failobj
  471.         
  472.         return ctype.split('/')[1]
  473.  
  474.     
  475.     def get_content_type(self):
  476.         """Return the message's content type.
  477.  
  478.         The returned string is coerced to lower case of the form
  479.         `maintype/subtype'.  If there was no Content-Type header in the
  480.         message, the default type as given by get_default_type() will be
  481.         returned.  Since according to RFC 2045, messages always have a default
  482.         type this will always return a value.
  483.  
  484.         RFC 2045 defines a message's default type to be text/plain unless it
  485.         appears inside a multipart/digest container, in which case it would be
  486.         message/rfc822.
  487.         """
  488.         missing = object()
  489.         value = self.get('content-type', missing)
  490.         if value is missing:
  491.             return self.get_default_type()
  492.         
  493.         ctype = paramre.split(value)[0].lower().strip()
  494.         if ctype.count('/') != 1:
  495.             return 'text/plain'
  496.         
  497.         return ctype
  498.  
  499.     
  500.     def get_content_maintype(self):
  501.         """Return the message's main content type.
  502.  
  503.         This is the `maintype' part of the string returned by
  504.         get_content_type().
  505.         """
  506.         ctype = self.get_content_type()
  507.         return ctype.split('/')[0]
  508.  
  509.     
  510.     def get_content_subtype(self):
  511.         """Returns the message's sub-content type.
  512.  
  513.         This is the `subtype' part of the string returned by
  514.         get_content_type().
  515.         """
  516.         ctype = self.get_content_type()
  517.         return ctype.split('/')[1]
  518.  
  519.     
  520.     def get_default_type(self):
  521.         """Return the `default' content type.
  522.  
  523.         Most messages have a default content type of text/plain, except for
  524.         messages that are subparts of multipart/digest containers.  Such
  525.         subparts have a default content type of message/rfc822.
  526.         """
  527.         return self._default_type
  528.  
  529.     
  530.     def set_default_type(self, ctype):
  531.         '''Set the `default\' content type.
  532.  
  533.         ctype should be either "text/plain" or "message/rfc822", although this
  534.         is not enforced.  The default content type is not stored in the
  535.         Content-Type header.
  536.         '''
  537.         self._default_type = ctype
  538.  
  539.     
  540.     def _get_params_preserve(self, failobj, header):
  541.         missing = object()
  542.         value = self.get(header, missing)
  543.         if value is missing:
  544.             return failobj
  545.         
  546.         params = []
  547.         for p in _parseparam(';' + value):
  548.             
  549.             try:
  550.                 (name, val) = p.split('=', 1)
  551.                 name = name.strip()
  552.                 val = val.strip()
  553.             except ValueError:
  554.                 name = p.strip()
  555.                 val = ''
  556.  
  557.             params.append((name, val))
  558.         
  559.         params = Utils.decode_params(params)
  560.         return params
  561.  
  562.     
  563.     def get_params(self, failobj = None, header = 'content-type', unquote = True):
  564.         """Return the message's Content-Type parameters, as a list.
  565.  
  566.         The elements of the returned list are 2-tuples of key/value pairs, as
  567.         split on the `=' sign.  The left hand side of the `=' is the key,
  568.         while the right hand side is the value.  If there is no `=' sign in
  569.         the parameter the value is the empty string.  The value is as
  570.         described in the get_param() method.
  571.  
  572.         Optional failobj is the object to return if there is no Content-Type
  573.         header.  Optional header is the header to search instead of
  574.         Content-Type.  If unquote is True, the value is unquoted.
  575.         """
  576.         missing = object()
  577.         params = self._get_params_preserve(missing, header)
  578.         if params is missing:
  579.             return failobj
  580.         
  581.  
  582.     
  583.     def get_param(self, param, failobj = None, header = 'content-type', unquote = True):
  584.         """Return the parameter value if found in the Content-Type header.
  585.  
  586.         Optional failobj is the object to return if there is no Content-Type
  587.         header, or the Content-Type header has no such parameter.  Optional
  588.         header is the header to search instead of Content-Type.
  589.  
  590.         Parameter keys are always compared case insensitively.  The return
  591.         value can either be a string, or a 3-tuple if the parameter was RFC
  592.         2231 encoded.  When it's a 3-tuple, the elements of the value are of
  593.         the form (CHARSET, LANGUAGE, VALUE).  Note that both CHARSET and
  594.         LANGUAGE can be None, in which case you should consider VALUE to be
  595.         encoded in the us-ascii charset.  You can usually ignore LANGUAGE.
  596.  
  597.         Your application should be prepared to deal with 3-tuple return
  598.         values, and can convert the parameter to a Unicode string like so:
  599.  
  600.             param = msg.get_param('foo')
  601.             if isinstance(param, tuple):
  602.                 param = unicode(param[2], param[0] or 'us-ascii')
  603.  
  604.         In any case, the parameter value (either the returned string, or the
  605.         VALUE item in the 3-tuple) is always unquoted, unless unquote is set
  606.         to False.
  607.         """
  608.         if not self.has_key(header):
  609.             return failobj
  610.         
  611.         for k, v in self._get_params_preserve(failobj, header):
  612.             if k.lower() == param.lower():
  613.                 if unquote:
  614.                     return _unquotevalue(v)
  615.                 else:
  616.                     return v
  617.             unquote
  618.         
  619.         return failobj
  620.  
  621.     
  622.     def set_param(self, param, value, header = 'Content-Type', requote = True, charset = None, language = ''):
  623.         '''Set a parameter in the Content-Type header.
  624.  
  625.         If the parameter already exists in the header, its value will be
  626.         replaced with the new value.
  627.  
  628.         If header is Content-Type and has not yet been defined for this
  629.         message, it will be set to "text/plain" and the new parameter and
  630.         value will be appended as per RFC 2045.
  631.  
  632.         An alternate header can specified in the header argument, and all
  633.         parameters will be quoted as necessary unless requote is False.
  634.  
  635.         If charset is specified, the parameter will be encoded according to RFC
  636.         2231.  Optional language specifies the RFC 2231 language, defaulting
  637.         to the empty string.  Both charset and language should be strings.
  638.         '''
  639.         if not isinstance(value, tuple) and charset:
  640.             value = (charset, language, value)
  641.         
  642.         if not self.has_key(header) and header.lower() == 'content-type':
  643.             ctype = 'text/plain'
  644.         else:
  645.             ctype = self.get(header)
  646.         if not self.get_param(param, header = header):
  647.             if not ctype:
  648.                 ctype = _formatparam(param, value, requote)
  649.             else:
  650.                 ctype = SEMISPACE.join([
  651.                     ctype,
  652.                     _formatparam(param, value, requote)])
  653.         else:
  654.             ctype = ''
  655.             for old_param, old_value in self.get_params(header = header, unquote = requote):
  656.                 append_param = ''
  657.                 if old_param.lower() == param.lower():
  658.                     append_param = _formatparam(param, value, requote)
  659.                 else:
  660.                     append_param = _formatparam(old_param, old_value, requote)
  661.                 if not ctype:
  662.                     ctype = append_param
  663.                     continue
  664.                 ctype = SEMISPACE.join([
  665.                     ctype,
  666.                     append_param])
  667.             
  668.         if ctype != self.get(header):
  669.             del self[header]
  670.             self[header] = ctype
  671.         
  672.  
  673.     
  674.     def del_param(self, param, header = 'content-type', requote = True):
  675.         '''Remove the given parameter completely from the Content-Type header.
  676.  
  677.         The header will be re-written in place without the parameter or its
  678.         value. All values will be quoted as necessary unless requote is
  679.         False.  Optional header specifies an alternative to the Content-Type
  680.         header.
  681.         '''
  682.         if not self.has_key(header):
  683.             return None
  684.         
  685.         new_ctype = ''
  686.         for p, v in self.get_params(header = header, unquote = requote):
  687.             if p.lower() != param.lower():
  688.                 if not new_ctype:
  689.                     new_ctype = _formatparam(p, v, requote)
  690.                 else:
  691.                     new_ctype = SEMISPACE.join([
  692.                         new_ctype,
  693.                         _formatparam(p, v, requote)])
  694.             new_ctype
  695.         
  696.         if new_ctype != self.get(header):
  697.             del self[header]
  698.             self[header] = new_ctype
  699.         
  700.  
  701.     
  702.     def set_type(self, type, header = 'Content-Type', requote = True):
  703.         '''Set the main type and subtype for the Content-Type header.
  704.  
  705.         type must be a string in the form "maintype/subtype", otherwise a
  706.         ValueError is raised.
  707.  
  708.         This method replaces the Content-Type header, keeping all the
  709.         parameters in place.  If requote is False, this leaves the existing
  710.         header\'s quoting as is.  Otherwise, the parameters will be quoted (the
  711.         default).
  712.  
  713.         An alternative header can be specified in the header argument.  When
  714.         the Content-Type header is set, we\'ll always also add a MIME-Version
  715.         header.
  716.         '''
  717.         if not type.count('/') == 1:
  718.             raise ValueError
  719.         
  720.         if header.lower() == 'content-type':
  721.             del self['mime-version']
  722.             self['MIME-Version'] = '1.0'
  723.         
  724.         if not self.has_key(header):
  725.             self[header] = type
  726.             return None
  727.         
  728.         params = self.get_params(header = header, unquote = requote)
  729.         del self[header]
  730.         self[header] = type
  731.         for p, v in params[1:]:
  732.             self.set_param(p, v, header, requote)
  733.         
  734.  
  735.     
  736.     def get_filename(self, failobj = None):
  737.         """Return the filename associated with the payload if present.
  738.  
  739.         The filename is extracted from the Content-Disposition header's
  740.         `filename' parameter, and it is unquoted.
  741.         """
  742.         missing = object()
  743.         filename = self.get_param('filename', missing, 'content-disposition')
  744.         if filename is missing:
  745.             return failobj
  746.         
  747.         return Utils.collapse_rfc2231_value(filename).strip()
  748.  
  749.     
  750.     def get_boundary(self, failobj = None):
  751.         """Return the boundary associated with the payload if present.
  752.  
  753.         The boundary is extracted from the Content-Type header's `boundary'
  754.         parameter, and it is unquoted.
  755.         """
  756.         missing = object()
  757.         boundary = self.get_param('boundary', missing)
  758.         if boundary is missing:
  759.             return failobj
  760.         
  761.         return Utils.collapse_rfc2231_value(boundary).rstrip()
  762.  
  763.     
  764.     def set_boundary(self, boundary):
  765.         """Set the boundary parameter in Content-Type to 'boundary'.
  766.  
  767.         This is subtly different than deleting the Content-Type header and
  768.         adding a new one with a new boundary parameter via add_header().  The
  769.         main difference is that using the set_boundary() method preserves the
  770.         order of the Content-Type header in the original message.
  771.  
  772.         HeaderParseError is raised if the message has no Content-Type header.
  773.         """
  774.         missing = object()
  775.         params = self._get_params_preserve(missing, 'content-type')
  776.         if params is missing:
  777.             raise Errors.HeaderParseError, 'No Content-Type header found'
  778.         
  779.         newparams = []
  780.         foundp = False
  781.         for pk, pv in params:
  782.             if pk.lower() == 'boundary':
  783.                 newparams.append(('boundary', '"%s"' % boundary))
  784.                 foundp = True
  785.                 continue
  786.             newparams.append((pk, pv))
  787.         
  788.         if not foundp:
  789.             newparams.append(('boundary', '"%s"' % boundary))
  790.         
  791.         newheaders = []
  792.         for h, v in self._headers:
  793.             if h.lower() == 'content-type':
  794.                 parts = []
  795.                 for k, v in newparams:
  796.                     if v == '':
  797.                         parts.append(k)
  798.                         continue
  799.                     parts.append('%s=%s' % (k, v))
  800.                 
  801.                 newheaders.append((h, SEMISPACE.join(parts)))
  802.                 continue
  803.             newheaders.append((h, v))
  804.         
  805.         self._headers = newheaders
  806.  
  807.     
  808.     def get_content_charset(self, failobj = None):
  809.         '''Return the charset parameter of the Content-Type header.
  810.  
  811.         The returned string is always coerced to lower case.  If there is no
  812.         Content-Type header, or if that header has no charset parameter,
  813.         failobj is returned.
  814.         '''
  815.         missing = object()
  816.         charset = self.get_param('charset', missing)
  817.         if charset is missing:
  818.             return failobj
  819.         
  820.         if isinstance(charset, tuple):
  821.             if not charset[0]:
  822.                 pass
  823.             pcharset = 'us-ascii'
  824.             charset = unicode(charset[2], pcharset).encode('us-ascii')
  825.         
  826.         return charset.lower()
  827.  
  828.     
  829.     def get_charsets(self, failobj = None):
  830.         '''Return a list containing the charset(s) used in this message.
  831.  
  832.         The returned list of items describes the Content-Type headers\'
  833.         charset parameter for this message and all the subparts in its
  834.         payload.
  835.  
  836.         Each item will either be a string (the value of the charset parameter
  837.         in the Content-Type header of that part) or the value of the
  838.         \'failobj\' parameter (defaults to None), if the part does not have a
  839.         main MIME type of "text", or the charset is not defined.
  840.  
  841.         The list will contain one string for each part of the message, plus
  842.         one for the container message (i.e. self), so that a non-multipart
  843.         message will still return a list of length 1.
  844.         '''
  845.         return [ part.get_content_charset(failobj) for part in self.walk() ]
  846.  
  847.     from email.Iterators import walk
  848.  
  849.